package com.northking.statisticsdemo.testOutResource;


import cn.hutool.core.io.FileUtil;
import com.northking.chainResponsibility.ChainEntryAnnotation;
import com.northking.chainResponsibility.ChainEntryInterface;
import org.reflections.Reflections;
import org.reflections.util.ConfigurationBuilder;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;

/**
 * @author BigHead
 * @date 2021/11/4 11:09
 * @description OthreDirResource
 */
public class OtherDirResource {
    public static void main(String[] args) throws Exception {
//        String path = "file:///E:\\coderHelp\\StatisticsDemo\\StatisticsCustomChain-0.0.1.jar";
        String path = "E:\\coderHelp\\StatisticsDemo\\StatisticsCustomChain-0.0.1.jar";
//        URL[] urls = new URL[]{new URL(path)};
//        URLClassLoader urlClassLoader = new URLClassLoader(urls);
//        ClassLoader[] cl = {new URLClassLoader(urls)};




        URLClassLoader classloader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
        Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        if (!addURL.isAccessible()){
            addURL.setAccessible(true);
        }
        File jarFile = FileUtil.file(path);
        addURL.invoke(classloader, jarFile.toURI().toURL());
        ClassLoader[] cl = {classloader};

//        Reflections reflections = new Reflections(
//                new ConfigurationBuilder()
//                        .setUrls(new URL(path))
//                        .setClassLoaders(cl)
//        );
        Reflections reflections = new Reflections("com.northking.chainResponsibility");
        Set<Class<?>> chainEntryClassSet = reflections.getTypesAnnotatedWith(ChainEntryAnnotation.class);
        Map<String, ChainEntryInterface> chainEntryTempMap = new HashMap<>(chainEntryClassSet.size());
        for (Class<?> clazz : chainEntryClassSet) {
            // 扫描 链路入口类
            final ChainEntryAnnotation chainEntryAnnotation = clazz.getAnnotation(ChainEntryAnnotation.class);
            // 生成链路入口类
            Class<? extends ChainEntryInterface> chainEntryInterfaceClass = chainEntryAnnotation.chainEntryClass();
            // 实例化链路入口类 TODO 这里相关mapper没有传入 后续优化
            ChainEntryInterface chainEntryInterface;
            try {
                chainEntryInterface = chainEntryInterfaceClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
                // 初始化异常这里应该增加log做输出，而且为了不影响正常使用，直接跳过
                continue;
            }
            chainEntryTempMap.put(
                    chainEntryInterfaceClass.getSimpleName(),
                    chainEntryInterface
            );
        }
        System.out.println(chainEntryTempMap);
    }
}
